<template>
  <Dialog v-model="dialogVisible" title="导入prompt模板">
    <div class="upload-content">
      <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl"
      :auto-upload="false"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload-filled" :size="60" :color="'#ccc'" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
          <div class="el-upload__tip text-center">
            <span class="text-14px">仅允许导入 xls、xlsx 格式文件。</span>
            <el-link
                :underline="false"
                style="font-size: 14px; vertical-align: baseline; margin-left: 10px;"
                type="primary"
                @click="importTemplate"
              >
                下载模板
              </el-link>
          </div>
      </template>
    </el-upload>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </template>
  </Dialog>
  <ImportResponse ref="ImportResponseRef" />
</template>
<script lang="ts" setup>
import { getAccessToken, getTenantId } from '@/utils/auth'
import { PromptApi } from '@/api/multiModel/prompt'
import ImportResponse from './ImportResponse.vue'
import download from '@/utils/download'

defineOptions({ name: 'PromptImport' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const uploadRef = ref()
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/multiModel/prompt/import'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  fileList.value = []
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emits = defineEmits(['success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    message.error(response.msg)
    return
  }
  openForm(response.data)
  // 拼接提示语
  // const data = response.data
  // let text = '上传成功数量：' + data.createPromptNames.length + ';'
  // for (let username of data.createPromptNames) {
  //   text += '< ' + username + ' >'
  // }
  // text += '\n' + '导入失败数量：' + Object.keys(data.failurePromptNames).length + ';'
  // for (const username in data.failurePromptNames) {
  //   text += '< ' + username + ': ' + data.failurePromptNames[username] + ' >'
  // }
  // message.alert(text)
  // 发送操作成功的事件
  emits('success')  
  dialogVisible.value = false
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
}

/** 添加/修改操作 */
const ImportResponseRef = ref()
const openForm = (data: any) => {
  ImportResponseRef.value.open(data)
}

// 

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('单次只能上传一个文件！')
}

/** 下载模板操作 */
const importTemplate = async () => {
  const res = await PromptApi.importPromptTemplate()
  download.excel(res, 'prompt导入模版.xls')
}

</script>

<style lang="scss" scoped>
.upload-content {
  padding: 10px 150px;
  .el-upload__text {
    line-height: 30px;
    font-size: 16px;
  }
}
</style>
